package com.longg.dao;

import com.longg.dao.base.BaseDao;
import com.longg.model.Dept;
import com.longg.utils.JDBCUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import javax.management.Query;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class DeptDao extends BaseDao<Dept> {
    public DeptDao() {
        super(Dept.class);
    }

    public List<Dept> findAll(){
        String sql = "select * from dept";
        QueryRunner queryRunner = new QueryRunner(JDBCUtil.getDataSource());
        List<Dept> deptList = null;
        try {
            deptList = queryRunner.query(sql,new BeanListHandler<>(Dept.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return deptList;
    }

    public List<Map<String,Object>> findDeptAndUser(){
        String sql = "select ui.user_id,IFNULL(ui.real_name,'匿名用户') as real_name,d.id,d.`name`\n" +
                "from user u,user_info ui,dept d\n" +
                "where u.dept_id is not null and u.dept_id = d.id and u.id = ui.user_id";
        QueryRunner queryRunner = new QueryRunner(JDBCUtil.getDataSource());
        List<Map<String,Object>> list = null;
        try {
            list = queryRunner.query(sql,new MapListHandler());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    public List<Map<String, Object>> getIdsById(int did) {
        String sql = "select u.id \n" +
                "from user u \n" +
                "where exists(select * from dept d where d.id = ? and u.dept_id = d.id)";
        QueryRunner queryRunner = new QueryRunner(JDBCUtil.getDataSource());
        List<Map<String, Object>> query = null;
        try {
            query = queryRunner.query(sql, new MapListHandler(), did);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }
}
